/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import Sound from 'react-native-sound';
import { AudioRecorder, AudioUtils } from 'react-native-audio';
var RNFS = require('react-native-fs');
import {
  StyleSheet,
  View,
  WebView,
  Dimensions,
  Text,
  Alert,
  TouchableOpacity,
  Platform,
  PermissionsAndroid,
  ActivityIndicator,
  Linking,
} from 'react-native';
import Util from './uploadFile';
import JPushModule from 'jpush-react-native'
const {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get('window');
export default class TestRecordAudio extends Component {
  webview = undefined;
  constructor(props) {
    super(props);
    this.state = {
      camera: false,
      currentTime: 0.0,                                                   //开始录音到现在的持续时间
      recording: false,                                                   //是否正在录音
      stoppedRecording: false,                                            //是否停止了录音
      finished: false,                                                    //是否完成录音
      audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac',          //路径下的文件名
      hasPermission: undefined,                                           //是否获取权限
      showLoad: false
    };
    this.prepareRecordingPath = this.prepareRecordingPath.bind(this);     //执行录音的方法
    this.checkPermission = this.checkPermission.bind(this);               //检测是否授权
    this.record = this.record.bind(this);                                 //录音
    this.stop = this.stop.bind(this);                                     //停止
    this.play = this.play.bind(this);                                     //播放
    this.pause = this.pause.bind(this);                                   //暂停
    this.finishRecording = this.finishRecording.bind(this);
  }
  render() {
    //const scripts = "document.addEventListener('message',function (e){eval(e.data);});"
    const scripts = "alert(333)";
    const { camera } = this.state;
    console.log('version---', Platform.Version);
    return (
      <View style={styles.container}>
        {
          this.state.showLoad && <View style={{ flex: 1, position: 'absolute' }}><ActivityIndicator size="large" color="#0000ff" /></View>
        }
        {
          (() => {
            if (!camera) {
              return (<WebView
                ref={webview => this.webview = webview}
                startInLoadingState={true}
                renderLoading={() => {
                  return (
                    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><ActivityIndicator size="large" color="#0000ff" /></View>
                  )
                }}
                style={{
                  flex: 1,
                  height: deviceHeight,
                  width: deviceWidth
                }}
                source={{ uri: 'http://192.168.95.43:3000/home/4001', method: 'GET' }}
                javaScriptEnabled={true}
                onMessage={this.onBridgeMessage.bind(this)}
                //injectedJavaScript={scripts}
                injectedJavaScript={scripts}
              />);
            } else {
              // return <Scan back={this.onBack.bind(this)} />;
              return (
                <View style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', width: deviceWidth }}>
                  <TouchableOpacity style={{ margin: 40, padding: 10, borderWidth: 1, display: 'flex', width: deviceWidth * 0.8, justifyContent: 'center', alignItems: 'center', borderColor: '#00ff00', borderStyle: 'solid' }} onPress={this.record}>
                    <Text>录 音</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={{ margin: 40, padding: 10, borderWidth: 1, display: 'flex', width: deviceWidth * 0.8, justifyContent: 'center', alignItems: 'center', borderColor: '#00ff00', borderStyle: 'solid' }} onPress={this.stop}>
                    <Text>停止录音</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={{ margin: 40, padding: 10, borderWidth: 1, display: 'flex', width: deviceWidth * 0.8, justifyContent: 'center', alignItems: 'center', borderColor: '#00ff00', borderStyle: 'solid' }} onPress={this.pause}>
                    <Text>暂停录音</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={{ margin: 40, padding: 10, borderWidth: 1, display: 'flex', width: deviceWidth * 0.8, justifyContent: 'center', alignItems: 'center', borderColor: '#00ff00', borderStyle: 'solid' }} onPress={this.play}>
                    <Text>播放录音</Text>
                  </TouchableOpacity>
                </View>
              )
            }
          })()
        }
      </View>
    );
  }
  loadEnd() {
    this.setState = {
      showLoad: false
    }
  }
  readFile(path) {
    // create a path you want to delete
    //const path = RNFS.MainBundlePath + '/test.txt';
    return RNFS.readFile(path)
      .then((result) => {
        console.log(result);

        this.setState({
          readTxtResult: result,
        })
      })
      .catch((err) => {
        console.log(err.message);

      });
  }
  prepareRecordingPath(audioPath) {
    AudioRecorder.prepareRecordingAtPath(audioPath, {
      SampleRate: 22050,
      Channels: 1,
      AudioQuality: "Low",            //录音质量
      AudioEncoding: "aac",           //录音格式
      AudioEncodingBitRate: 32000     //比特率
    });
  }

  checkPermission() {
    if (Platform.OS !== 'android') {
      return Promise.resolve(true);
    }
    const rationale = {
      'title': '获取录音权限',
      'message': 'XXX正请求获取麦克风权限用于录音,是否准许'
    };

    return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, rationale)
      .then((result) => {
        // alert(result);     //结果: granted ,    PermissionsAndroid.RESULTS.GRANTED 也等于 granted
        return (result === true || PermissionsAndroid.RESULTS.GRANTED)
      })
  }

  async record() {
    // 如果正在录音
    if (this.state.recording) {
      alert('正在录音中!');
      return;
    }

    //如果没有获取权限
    if (!this.state.hasPermission) {
      alert('没有获取录音权限!');
      return;
    }

    //如果暂停获取停止了录音
    if (this.state.stoppedRecording) {
      this.prepareRecordingPath(this.state.audioPath);
    }

    this.setState({ recording: true });

    try {
      const filePath = await AudioRecorder.startRecording();
    } catch (error) {
      console.error(error);
    }
  }

  async stop() {
    // 如果没有在录音
    if (!this.state.recording) {
      alert('没有录音, 无需停止!');
      return;
    }

    this.setState({ stoppedRecording: true, recording: false });

    try {
      const filePath = await AudioRecorder.stopRecording();
      if (Platform.OS === 'android') {
        this.finishRecording(true, filePath);
      }
      return filePath;
    } catch (error) {
      console.error(error);
    }

  }

  async play() {
    // 如果在录音 , 执行停止按钮
    if (this.state.recording) {
      await this.stop();
    }

    // 使用 setTimeout 是因为, 为避免发生一些问题 react-native-sound中
    setTimeout(() => {
      var sound = new Sound(this.state.audioPath, '', (error) => {
        if (error) {
          console.log('failed to load the sound', error);
        }
      });

      setTimeout(() => {
        sound.play((success) => {
          if (success) {
            console.log('successfully finished playing');
          } else {
            console.log('playback failed due to audio decoding errors');
          }
        });
      }, 100);
    }, 100);
  }

  async pause() {
    if (!this.state.recording) {
      alert('没有录音, 无需停止!');
      return;
    }

    this.setState({ stoppedRecording: true, recording: false });

    try {
      const filePath = await AudioRecorder.pauseRecording();
      // 在安卓中, 暂停就等于停止
      if (Platform.OS === 'android') {

        this.finishRecording(true, filePath);
      }
    } catch (error) {
      console.error(error);
    }
  }

  finishRecording(didSucceed, filePath) {
    let result = this.readFile(filePath);
    console.log('result----', result);
    Util.uploadFile(result);
    this.setState({ finished: didSucceed });
    console.log(`Finished recording of duration ${this.state.currentTime} seconds at path: ${filePath}`);
  }

  componentDidMount() {
    let a = "hotdog";
    this.webview.postMessage(a);
    // 页面加载完成后获取权限
    this.checkPermission().then((hasPermission) => {
      this.setState({ hasPermission });

      //如果未授权, 则执行下面的代码
      if (!hasPermission) return;
      this.prepareRecordingPath(this.state.audioPath);

      AudioRecorder.onProgress = (data) => {
        this.setState({ currentTime: Math.floor(data.currentTime) });
      };

      AudioRecorder.onFinished = (data) => {
        if (Platform.OS === 'ios') {
          this.finishRecording(data.status === "OK", data.audioFileURL);
        }
      };

    });
    // console.log(this.props.navigator)
    // console.log(audioPath)
    /****************************通知 start **************************************************/
    if (Platform.OS === 'android') {
      JPushModule.initPush()
      // 新版本必需写回调函数
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
        }
      })
    } else {
      JPushModule.setupPush()
    }
    // 接收自定义消息
    this.receiveCustomMsgListener = map => {
      this.setState({
        pushMsg: map.content
      })
      console.log('extras: ' + map.extras)
    }

    // 接收自定义消息JPushModule.addReceiveCustomMsgListener(this.receiveCustomMsgListener)
    this.receiveNotificationListener = map => {
      console.log('alertContent: ' + map.alertContent)
      console.log('extras: ' + map.extras)
    }
    // 接收推送通知
    JPushModule.addReceiveNotificationListener(this.receiveNotificationListener)
    // 打开通知
    this.openNotificationListener = map => {
      console.log('Opening notification!')
      console.log('map.extra: ' + map.extras)
      alert("打开了通知");
      // let webUrl = JSON.parse(map.extras).webUrl;
      // let url = webUrl.replace(new RegExp("\/", 'g'), "/")
      // Linking.canOpenURL(url).then(supported => {
      //   if (!supported) {
      //     Alert.alert('您的系统不支持打开浏览器！')
      //   } else {
      //     return Linking.openURL(url);
      //   }
      // }).catch(err => { });

    }
    JPushModule.addReceiveOpenNotificationListener(this.openNotificationListener)

    // this.getRegistrationIdListener = registrationId => {
    //   console.log('Device register succeed, registrationId ' + registrationId)
    // }
    // JPushModule.addGetRegistrationIdListener(this.getRegistrationIdListener)
    /****************************通知 end **************************************************/

  }
  componentWillUnmount() {
    JPushModule.removeReceiveCustomMsgListener(this.receiveCustomMsgListener)
    JPushModule.removeReceiveNotificationListener(this.receiveNotificationListener)
    JPushModule.removeReceiveOpenNotificationListener(this.openNotificationListener)
    // JPushModule.removeGetRegistrationIdListener(this.getRegistrationIdListener)
    // console.log('Will clear all notifications')
    // JPushModule.clearAllNotifications()
  }
  onBridgeMessage(e) {
    if (e.nativeEvent.data === "record") {
      // const camera = true;
      //this.setState({ camera });
      this.record();
      this.webview.postMessage(this.state.audioPath);
    } else if (e.nativeEvent.data === "pause") {
      this.stop();
    } else {
      this.play();
    }

  }

  onBack(camera) {
    Alert.alert("提示", "返回");
    camera = false;
    this.setState({ camera });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});
